﻿package com.firewolf.hibernate.extend.subclass;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class MainDriver {

	private SessionFactory sessionFactory;
	private Session session;
	private Transaction transaction;
	
	@Before
	public void init(){
		Configuration configuration = new Configuration().configure("com/firewolf/hibernate/extend/subclass/subclass.cfg.xml");
		ServiceRegistry serviceRegistry = 
				new ServiceRegistryBuilder().applySettings(configuration.getProperties())
				                            .buildServiceRegistry();
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		
		session = sessionFactory.openSession();
		transaction = session.beginTransaction();
	}
	
	@After
	public void destroy(){
		transaction.commit();
		session.close();
		sessionFactory.close();
	}
	
	@Test
	public void testCreate(){
	}
	
	/**
	 * 新增操作:
	 * 		1.子类和父类的数据都插入到了同一张表中，两者由辨别 者列来区别；
	 * 		2.辨别者列由Hibernate自动维护，不需要我们去管
	 */
	@Test
	public void testSave(){
		Person person = new Person();
		person.setName("AA");
		person.setAge(1);
		
		Student student = new Student();
		student.setName("name1");
		student.setAge(2);
		student.setSchool("school1");
		
		session.save(person);
		session.save(student);
	}
	
	/**
	 * 查询：
	 * 		1.查询父类记录，只需要查询一张表；
	 * 		2.查询子类记录，也只需查一张表
	 */
	@Test
	public void testQuery(){
		List<Person> psrsons = session.createQuery("FROM Person").list();
		System.out.println(psrsons.size());
		
		List<Student> students = session.createQuery("FROM Student").list();
		System.out.println(students.size());
	}
}
